package com.jspx.security.asymmetric;

import com.jspx.security.utils.EncryptUtil;

/**
 * Created by Administrator on 2017/5/9.
 *
 */
public abstract class AbstractEncrypt implements AsyEncrypt
{

    //SHA1WithRSA  MD5WithRSA
    protected String signAlgorithm = "MD5WithRSA";

    /**
     * 密钥长度，DH算法的默认密钥长度是1024
     * 密钥长度必须是64的倍数，在512到1024位之间
     * */
    protected static final int KEY_SIZE = 1024;
    /**
     * 签名算法
     * SHA1WithRSA
     * MD5withRSA
     */
    public void setSignAlgorithm(String signAlgorithm) {
        this.signAlgorithm = signAlgorithm;
    }

    //字符串模式为16进制字符串
    public String sign(String data, String privateKey) throws Exception
    {
        return  EncryptUtil.byteToHex(sign(EncryptUtil.hexToByte(data),EncryptUtil.hexToByte(privateKey)));
    }

    public String base64Sign(String data, String privateKey) throws Exception
    {
        return  EncryptUtil.getBase64Encode(sign(EncryptUtil.getBase64Decode(data),EncryptUtil.getBase64Decode(privateKey)),EncryptUtil.NO_WRAP);
    }

    public boolean verify(String data, String publicKey, String sign) throws Exception
    {
        return verify(EncryptUtil.hexToByte(data),EncryptUtil.hexToByte(publicKey),EncryptUtil.hexToByte(sign));
    }

    public boolean base64Verify(String data, String publicKey, String sign) throws Exception
    {
        return verify(EncryptUtil.getBase64Decode(data),EncryptUtil.getBase64Decode(publicKey),EncryptUtil.getBase64Decode(sign));
    }

    public String encryptByPublicKey(String data, String publicKey) throws Exception
    {
        return  EncryptUtil.byteToHex(encryptByPublicKey(EncryptUtil.hexToByte(data),EncryptUtil.hexToByte(publicKey)));
    }

    public String base64EncryptByPublicKey(String data, String publicKey) throws Exception
    {
        return  EncryptUtil.getBase64Encode(encryptByPublicKey(EncryptUtil.getBase64Decode(data),EncryptUtil.getBase64Decode(publicKey)),EncryptUtil.NO_WRAP);
    }

    public String decryptByPrivateKey(String data, String privateKey)  throws Exception
    {
        return  EncryptUtil.byteToHex(decryptByPrivateKey(EncryptUtil.hexToByte(data),EncryptUtil.hexToByte(privateKey)));
    }

    public String base64DecryptByPrivateKey(String data, String privateKey)  throws Exception
    {
        return  EncryptUtil.getBase64Encode(decryptByPrivateKey(EncryptUtil.getBase64Decode(data),EncryptUtil.getBase64Decode(privateKey)),EncryptUtil.NO_WRAP);
    }

}
